<template>
  <div class="manage-clubs">
    <div class="page-header">
      <h1>社团管理</h1>
      <el-button type="primary" @click="openAddDialog">添加新社团</el-button>
    </div>

    <!-- 搜索和过滤 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索社团名称"
        prefix-icon="el-icon-search"
        clearable
        @clear="loadClubs"
        @keyup.enter="searchClubs"
      ></el-input>
      <el-button type="primary" @click="searchClubs">搜索</el-button>
    </div>

    <!-- 社团列表 -->
    <el-table
      :data="clubs"
      style="width: 100%"
      border
      stripe
      :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
      :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
      v-loading="loading"
    >
      <el-table-column prop="_id" label="ID" width="240"></el-table-column>
      <el-table-column prop="clubname" label="社团名称" width="180"></el-table-column>
      <el-table-column label="社团图标" width="120">
        <template #default="scope">
          <img
            :src="scope.row.clubimg ? `http://localhost:5000/uploads/${scope.row.clubimg}` : defaultClubImage"
            alt="社团图标"
            style="width: 50px; height: 50px; border-radius: 50%; object-fit: cover;"
            @error="handleImageError"
          >
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述">
        <template #default="scope">
          <div class="description-cell">{{ scope.row.description || '无描述' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="所属学校" width="180">
        <template #default="scope">
          {{ scope.row.school ? scope.row.school.name : '未分配' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="editClub(scope.row)"
          >编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="confirmDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="totalItems"
        background
      ></el-pagination>
    </div>

    <!-- 添加/编辑社团对话框 -->
    <el-dialog
      :title="isEditing ? '编辑社团' : '添加新社团'"
      v-model="showDialog"
      width="50%"
      :close-on-click-modal="false"
      @close="resetForm"
    >
      <el-form :model="clubForm" :rules="clubRules" ref="clubFormRef" label-width="100px">
        <el-form-item label="社团名称" prop="clubname">
          <el-input v-model="clubForm.clubname"></el-input>
        </el-form-item>
        <el-form-item label="所属学校" prop="school">
          <el-select v-model="clubForm.school" placeholder="请选择学校" filterable style="width: 100%;">
            <el-option
              v-for="school in schools"
              :key="school._id"
              :label="school.name"
              :value="school._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="社团图标">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            @change="handleFileChange"
            accept="image/jpeg, image/png"
            ref="uploadRef"
          >
            <img v-if="clubForm.clubimgPreview" :src="clubForm.clubimgPreview" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span v-if="!clubForm.clubimgPreview && clubForm.clubimg" style="margin-left: 10px; color: #999;">当前图标: {{ clubForm.clubimg.substring(0, 10) }}...</span>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="clubForm.description" type="textarea" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitClub" :loading="submitting">{{ isEditing ? '保存' : '确定' }}</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      v-model="showDeleteDialog"
      width="30%"
    >
      <p>确定要删除社团 "{{ clubToDelete?.clubname }}" 吗？此操作不可撤销。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="deleteClub" :loading="deleting">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
import defaultClubImage from '@/assets/shehui.png'; // 导入默认图片

// 状态变量
const clubs = ref([]);
const schools = ref([]);
const loading = ref(false);
const submitting = ref(false);
const deleting = ref(false);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);
const showDialog = ref(false);
const isEditing = ref(false);
const showDeleteDialog = ref(false);
const clubToDelete = ref(null);
const clubFormRef = ref(null);
const uploadRef = ref(null);
const clubLogoFile = ref(null);

// 社团表单 (使用 reactive)
const clubForm = reactive({
  _id: '',
  clubname: '',
  clubimg: '',
  clubimgPreview: '',
  description: '',
  school: '',
});

// 表单验证规则
const clubRules = {
  clubname: [
    { required: true, message: '请输入社团名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  school: [
    { required: true, message: '请选择所属学校', trigger: 'change' }
  ],
  description: [
    { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
  ]
};

// 加载学校列表
const loadSchools = async () => {
  try {
    const response = await axios.get('http://localhost:5000/school');
    schools.value = response.data || [];
  } catch (error) {
    console.error('获取学校列表失败:', error);
    ElMessage.error('获取学校列表失败');
  }
};

// 加载社团数据
const loadClubs = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      search: searchQuery.value.trim() || undefined
    };
    const response = await axios.get('http://localhost:5000/clubs', { params });

    clubs.value = response.data.clubs || [];
    totalItems.value = response.data.pagination.total || 0;

  } catch (error) {
    console.error('获取社团列表失败:', error);
    ElMessage.error('获取社团列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索社团 (触发带搜索条件的加载)
const searchClubs = async () => {
  currentPage.value = 1;
  await loadClubs();
};

// 分页变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  loadClubs();
};

// 打开添加对话框
const openAddDialog = () => {
  isEditing.value = false;
  resetForm();
  showDialog.value = true;
};

// 编辑社团
const editClub = (club) => {
  isEditing.value = true;
  Object.assign(clubForm, {
    _id: club._id,
    clubname: club.clubname,
    description: club.description || '',
    school: club.school?._id || '',
    clubimg: club.clubimg || '',
    clubimgPreview: club.clubimg ? `http://localhost:5000/uploads/${club.clubimg}` : ''
  });
  clubLogoFile.value = null;
  showDialog.value = true;
};

// 确认删除
const confirmDelete = (club) => {
  clubToDelete.value = club;
  showDeleteDialog.value = true;
};

// 删除社团
const deleteClub = async () => {
  if (!clubToDelete.value || !clubToDelete.value._id) return;
  deleting.value = true;
  try {
    await axios.delete(`http://localhost:5000/clubs/${clubToDelete.value._id}`);
    ElMessage.success('删除成功');
    showDeleteDialog.value = false;
    clubToDelete.value = null;
    if (clubs.value.length === 1 && currentPage.value > 1) {
      currentPage.value--;
    }
    await loadClubs();
  } catch (error) {
    console.error('删除社团失败:', error);
    ElMessage.error(`删除社团失败: ${error.response?.data?.message || error.message}`);
  } finally {
    deleting.value = false;
  }
};

// 重置表单
const resetForm = () => {
  clubForm._id = '';
  clubForm.clubname = '';
  clubForm.description = '';
  clubForm.school = '';
  clubForm.clubimg = '';
  clubForm.clubimgPreview = '';
  clubLogoFile.value = null;
  if (clubFormRef.value) {
    clubFormRef.value.resetFields();
  }
};

// 提交社团（添加或更新）
const submitClub = async () => {
  if (!clubFormRef.value) return;

  await clubFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      const formData = new FormData();
      formData.append('clubname', clubForm.clubname);
      formData.append('description', clubForm.description);
      formData.append('school', clubForm.school);
      if (clubLogoFile.value) {
        formData.append('clubimg', clubLogoFile.value);
      }

      try {
        if (isEditing.value) {
          await axios.put(`http://localhost:5000/clubs/${clubForm._id}`, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          });
          ElMessage.success('更新成功');
        } else {
          await axios.post('http://localhost:5000/clubs', formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          });
          ElMessage.success('添加成功');
        }
        showDialog.value = false;
        await loadClubs();
      } catch (error) {
        console.error(isEditing.value ? '更新社团失败:' : '添加社团失败:', error);
        ElMessage.error(`${isEditing.value ? '更新' : '添加'}社团失败: ${error.response?.data?.message || error.message}`);
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 处理文件选择变化
const handleFileChange = (uploadFile) => {
  const file = uploadFile.raw;
  if (file && beforeAvatarUpload(file)) {
    clubLogoFile.value = file;
    const reader = new FileReader();
    reader.onload = (e) => {
      clubForm.clubimgPreview = e.target.result;
    };
    reader.readAsDataURL(file);
  } else if (!file) {
    clubLogoFile.value = null;
    if (isEditing.value && clubForm.clubimg) {
      clubForm.clubimgPreview = `http://localhost:5000/uploads/${clubForm.clubimg}`;
    } else {
      clubForm.clubimgPreview = '';
    }
  }
};

// 上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return (isJPG || isPNG) && isLt2M;
};

// 处理表格中图片加载错误
const handleImageError = (event) => {
  event.target.src = defaultClubImage; // 替换为导入的默认图片变量
};

// 组件加载时获取社团和学校列表
onMounted(() => {
  loadClubs();
  loadSchools();
});
</script>

<style scoped>
.manage-clubs {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #ffffff;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-bar .el-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.description-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: inline-block;
  vertical-align: top;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style>
